﻿using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudStorageLight.DesktopTool
{
    public class PresentationImageConverter : DocumentImageConverter
    {
        public PresentationImageConverter()
        {
        }

        public override bool ToXpsFile(string inputFile, string outputPatternFile, int pageSize)
        {
            var pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();
            
            Microsoft.Office.Interop.PowerPoint.Presentation pptPresentation = null;
            var xpsfile = GetExtnsionFilename(outputPatternFile, "xps");
            var outfile = GetExtnsionFilename(outputPatternFile, "jpg");
            try
            {
                pptPresentation = pptApplication.Presentations.Open(inputFile, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
                if (pptPresentation.Slides.Count < pageSize) pageSize = pptPresentation.Slides.Count;
                pptPresentation.ExportAsFixedFormat(
                    GetExtnsionFilename(outputPatternFile, "xps"),
                    PpFixedFormatType.ppFixedFormatTypeXPS,
                    PpFixedFormatIntent.ppFixedFormatIntentScreen, MsoTriState.msoFalse,
                    PpPrintHandoutOrder.ppPrintHandoutVerticalFirst, PpPrintOutputType.ppPrintOutputSlides,
                    MsoTriState.msoFalse, pptPresentation.PrintOptions.Ranges.Add(1, pageSize), PpPrintRangeType.ppPrintSlideRange, string.Empty, false, true, true, true, false,
                    Type.Missing);
                return true;

            }
            finally
            {
                if (pptPresentation != null)
                {
                    pptPresentation.Close();
                    pptPresentation = null;
                }
                if (pptApplication != null)
                {
                    pptApplication.Quit();
                    pptApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

        }
    }
}
